const mockDatabase = require('../config/mockDatabase');

class ReportConfig {
  constructor(data) {
    this.id = data.id;
    this.report_key = data.report_key;
    this.report_name = data.report_name;
    this.report_name_en = data.report_name_en;
    this.category = data.category;
    this.description = data.description;
    this.fields = data.fields;
    this.filters = data.filters;
    this.dimensions = data.dimensions;
    this.default_time_range = data.default_time_range;
    this.refresh_interval = data.refresh_interval;
    this.cache_duration = data.cache_duration;
    this.is_active = data.is_active;
    this.sort_order = data.sort_order;
    this.created_at = data.created_at;
    this.updated_at = data.updated_at;
  }

  // 获取所有报表配置
  static async findAll(filters = {}) {
    try {
      let configs = mockDatabase.reportConfigs || [];
      
      // 应用筛选条件
      if (filters.category) {
        configs = configs.filter(config => config.category === filters.category);
      }
      
      if (filters.is_active !== undefined) {
        configs = configs.filter(config => config.is_active === filters.is_active);
      }
      
      // 按排序字段排序
      configs.sort((a, b) => a.sort_order - b.sort_order);
      
      return configs.map(config => new ReportConfig(config));
    } catch (error) {
      console.error('Error finding report configs:', error);
      throw error;
    }
  }

  // 根据report_key获取报表配置
  static async findByKey(reportKey) {
    try {
      const configs = mockDatabase.reportConfigs || [];
      const config = configs.find(c => c.report_key === reportKey && c.is_active);
      
      return config ? new ReportConfig(config) : null;
    } catch (error) {
      console.error('Error finding report config by key:', error);
      throw error;
    }
  }

  // 根据分类获取报表配置
  static async findByCategory(category) {
    try {
      const configs = mockDatabase.reportConfigs || [];
      const categoryConfigs = configs.filter(c => c.category === category && c.is_active);
      
      // 按排序字段排序
      categoryConfigs.sort((a, b) => a.sort_order - b.sort_order);
      
      return categoryConfigs.map(config => new ReportConfig(config));
    } catch (error) {
      console.error('Error finding report configs by category:', error);
      throw error;
    }
  }

  // 创建新的报表配置
  static async create(configData) {
    try {
      if (!mockDatabase.reportConfigs) {
        mockDatabase.reportConfigs = [];
      }
      
      const newConfig = {
        id: mockDatabase.reportConfigs.length + 1,
        ...configData,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };
      
      mockDatabase.reportConfigs.push(newConfig);
      return new ReportConfig(newConfig);
    } catch (error) {
      console.error('Error creating report config:', error);
      throw error;
    }
  }

  // 更新报表配置
  static async update(reportKey, updateData) {
    try {
      const configs = mockDatabase.reportConfigs || [];
      const configIndex = configs.findIndex(c => c.report_key === reportKey);
      
      if (configIndex === -1) {
        throw new Error('Report config not found');
      }
      
      configs[configIndex] = {
        ...configs[configIndex],
        ...updateData,
        updated_at: new Date().toISOString()
      };
      
      return new ReportConfig(configs[configIndex]);
    } catch (error) {
      console.error('Error updating report config:', error);
      throw error;
    }
  }

  // 删除报表配置（软删除）
  static async delete(reportKey) {
    try {
      const configs = mockDatabase.reportConfigs || [];
      const configIndex = configs.findIndex(c => c.report_key === reportKey);
      
      if (configIndex === -1) {
        throw new Error('Report config not found');
      }
      
      configs[configIndex].is_active = false;
      configs[configIndex].updated_at = new Date().toISOString();
      
      return true;
    } catch (error) {
      console.error('Error deleting report config:', error);
      throw error;
    }
  }

  // 获取报表分类统计
  static async getCategoryStats() {
    try {
      const configs = mockDatabase.reportConfigs || [];
      const activeConfigs = configs.filter(c => c.is_active);
      
      const stats = {
        total: activeConfigs.length,
        financial: activeConfigs.filter(c => c.category === 'financial').length,
        sales: activeConfigs.filter(c => c.category === 'sales').length,
        product: activeConfigs.filter(c => c.category === 'product').length,
        customer_service: activeConfigs.filter(c => c.category === 'customer_service').length
      };
      
      return stats;
    } catch (error) {
      console.error('Error getting category stats:', error);
      throw error;
    }
  }

  // 验证报表配置数据
  static validateConfig(configData) {
    const errors = [];
    
    if (!configData.report_key) {
      errors.push('report_key is required');
    }
    
    if (!configData.report_name) {
      errors.push('report_name is required');
    }
    
    if (!configData.category || !['financial', 'sales', 'product', 'customer_service'].includes(configData.category)) {
      errors.push('Valid category is required');
    }
    
    if (!configData.fields || !Array.isArray(configData.fields)) {
      errors.push('fields must be an array');
    }
    
    return errors;
  }
}

module.exports = ReportConfig;